/**
 * Created by lihao on 2017/6/20.
 */
'use strict';
var keystone = require('keystone');
var session = require('keystone/lib/session');
exports = module.exports = function (req, res) {
	if (!req.body.userName || !req.body.password) {
		return res.json({code: 0, message: '请填写用户名和密码'});
	}
	var User = keystone.list(keystone.get('user model'));
	User.model.findOne({ userName: req.body.userName }).populate('message').exec(function (err, user) {
		if (user) {
			keystone.callHook(user, 'pre:signin', function (err) {
				if (err) return res.json({ code: 0, message: '登录失败' });
				user._.password.compare(req.body.password, function (err, isMatch) {
					if (isMatch) {
						session.signinWithUser(user, req, res, function () {
							keystone.callHook(user, 'post:signin', function (err) {
								if (err) return res.json({ code: 0, message: '登录失败' });
								res.json({ code: 1, message:'登录成功', data: user });
							});
						});
					} else if (err) {
						return res.json({  code: 0, error: 'bcrypt error', detail: err });
					} else {
						return res.json({  code: 0, message: '用户名或密码错误' });
					}
				});
			})
		}else if (err) {
			return res.json({ code: 0, message: '用户不存在' });
		} else {
			return res.json({ code: 0, message: '系统错误' });
		}
	});
	
};
